package com.laomuji.android.mvvm.base

import android.app.Application
import com.laomuji.android.mvvm.utils.MyLog

/**
 * 所有Application都要继承该类
 * @author laomuji666
 * @since 2024/2/20
 */
class BaseApplication :Application() {
    companion object{
        var instance:BaseApplication? = null
    }

    val activityList: ArrayList<BaseActivity<*, *>> = ArrayList()

    override fun onCreate() {
        super.onCreate()
        if(instance != null){
            MyLog.eCustom("tag_application", "Application重复初始化,请注意SDK是否需要重复初始化")
        }
        instance = this
    }

    /**
     * 获取当前顶部的Activity
     */
    fun getTopActivity(): BaseActivity<*, *> {
        return activityList[activityList.size - 1]
    }

    /**
     * 添加activity
     * 在Activity的onCreate中调用
     * @param activity 需要添加的activity
     */
    fun addActivity(activity: BaseActivity<*, *>) {
        activityList.add(activity)
    }

    /**
     * 移除activity
     * 在Activity的onDestroy中调用
     * @param activity 需要移除的activity
     */
    fun removeActivity(activity: BaseActivity<*, *>) {
        activityList.remove(activity)
    }

    /**
     * 退出App
     * finish所有的activity
     */
    fun exitApp() {
        for (baseActivity in activityList) {
            baseActivity.finish()
        }
        Runtime.getRuntime().exit(0)
    }

    /**
     * finish其他Activity
     * @param activity 不 finish 的 Activity
     */
    fun finishOtherActivity(activity: BaseActivity<*, *>) {
        for (baseActivity in activityList) {
            if (activity != baseActivity) {
                baseActivity.finish()
            }
        }
    }

}